package com.ruoyi.service.schedule.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.enums.YesNoEnum;
import com.ruoyi.service.project.entity.ProjectLaborEntity;
import com.ruoyi.service.schedule.entity.UserScheduleEntity;
import com.ruoyi.service.schedule.enums.ScheduleType;
import com.ruoyi.service.schedule.mapper.UserScheduleMapper;
import com.ruoyi.service.schedule.service.UserScheduleService;
import java.time.LocalDateTime;
import java.util.Objects;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户档期 服务实现类
 * </p>
 *
 * @author Zane
 * @since 2025-11-04
 */
@Service
public class UserScheduleServiceImpl extends ServiceImpl<UserScheduleMapper, UserScheduleEntity>
    implements UserScheduleService {

  @Override
  public void saveSchedule(ProjectLaborEntity laborEntity, LocalDateTime beginTime) {
    //判断用户当期是否存在
    UserScheduleEntity scheduleEntity = this.getOne(effectQuery()
        .eq(UserScheduleEntity::getUserId, laborEntity.getLaborId())
        .eq(UserScheduleEntity::getScheduleType, ScheduleType.PROJECT.getCode())
        .eq(UserScheduleEntity::getTraceId, laborEntity.getProjectId()), false);
    final UserScheduleEntity schedule = initSchedule(laborEntity, beginTime);
    if (Objects.nonNull(scheduleEntity)) {
      schedule.setId(scheduleEntity.getId())
          .setCreateBy(scheduleEntity.getCreateBy())
          .setCreateTime(scheduleEntity.getCreateTime());
      //      scheduleEntity.setStartTime(beginTime)
      //          .setEndTime(beginTime.plusDays(laborEntity.getRealDays()))
      //          .setRangeDay(laborEntity.getRealDays())
      //          .setUpdateBy(laborEntity.getUpdateBy())
      //          .setUpdateTime(LocalDateTime.now());
    }
    this.saveOrUpdate(scheduleEntity);
  }

  private UserScheduleEntity initSchedule(ProjectLaborEntity laborEntity, LocalDateTime beginTime) {
    return new UserScheduleEntity()
        .setUserId(laborEntity.getLaborId())
        .setScheduleType(ScheduleType.PROJECT.getCode())
        .setStartTime(beginTime)
        .setEndTime(beginTime.plusDays(laborEntity.getRealDays()))
        .setRangeDay(laborEntity.getRealDays())
        .setTraceId(laborEntity.getId())
        .setProjectId(laborEntity.getProjectId())
        .setCreateBy(laborEntity.getUpdateBy())
        .setCreateTime(LocalDateTime.now())
        .setUpdateBy(laborEntity.getUpdateBy())
        .setUpdateTime(LocalDateTime.now());
  }

  private LambdaQueryWrapper<UserScheduleEntity> effectQuery() {
    return new LambdaQueryWrapper<UserScheduleEntity>()
        .eq(UserScheduleEntity::getDelFlag, YesNoEnum.NO.getCode());
  }
}
